<template>
  <el-dialog
    v-model="visible"
    v-if="load"
    title="编辑SKU名称"
    width="1200"
    draggable
    @close="close"
    :z-index="2000"
  >
    <div class="flex justify-end">
      <div class="flex p-3">
        <el-button class="mr-3" type="primary" link @click="translate"
          >一键翻译</el-button
        >
        <el-select
          v-model="languages"
          collapse-tags
          placeholder="请选择"
          clearable
          multiple
          class="!w-[200px]"
          @change="changeLang"
        >
          <el-option
            v-for="item in languageOptions &&
            languageOptions.filter((item) => !(item.id === 1 || item.id === 2))"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </div>
    </div>
    <div class="border-t border-l border-r">
      <div
        class="flex-auto flex w-full"
        v-for="(item, index) in initGoodSku"
        :key="index"
      >
        <div class="itemStyle flex-auto">
          <div
            class="borHeader border-b border-r h-12 text-center leading-10"
            v-if="index == 0"
          >
            序号
          </div>
          <div class="inputStyle p-3 border-r border-b">
            {{ index + 1 }}
          </div>
        </div>
        <div class="itemStyle flex-auto w-190">
          <div
            class="borHeader border-b border-r h-12 text-center leading-10"
            v-if="index == 0"
          >
            SKU
          </div>
          <el-tooltip
            class="item"
            effect="dark"
            :content="item.sku || item.custom_sku"
            placement="top"
          >
            <div class="inputStyle p-3 border-r border-b overflow-line2">
              {{ item.sku || item.custom_sku }}
            </div>
          </el-tooltip>
        </div>
        <div class="itemStyle flex-auto w-190">
          <div
            class="borHeader border-b border-r h-12 text-center leading-10"
            v-if="index == 0"
          >
            属性
          </div>
          <el-tooltip
            class="item"
            effect="dark"
            :content="item.goods_sku_title[0].specifications"
            placement="top"
          >
            <div class="inputStyle p-2 border-r border-b overflow-line2">
              {{ item.goods_sku_title[0].specifications }}
            </div>
          </el-tooltip>
        </div>
        <template v-for="(tab, t) in item.goods_sku_title" :key="t">
          <ItemSKU
            class="flex-auto"
            v-model="item.goods_sku_title[t]"
            :index="index"
          ></ItemSKU>
        </template>
      </div>
    </div>
    <template #footer>
      <div class="flex justify-center py-2">
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save()">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { reactive, toRefs } from "vue";
import ItemSKU from "./ItemSKU";
import { translationBatch } from "@/api/index";
import { ElMessage } from "element-plus";
const emit = defineEmits(["getSku"]);
import useCommonStore from "@/store/modules/common";
import { storeToRefs } from "pinia";
const commonStore = useCommonStore();
const { languageOptions } = storeToRefs(commonStore);

// let options = reactive(inject('options'))
let formData = reactive(inject("form"));
const languages = ref([]);
const data = reactive({
  initGoodSku: [],
  visible: false,
  load: false,
});
const { initGoodSku, visible, load } = toRefs(data);

const open = async () => {
  if (!load.value) {
    load.value = true;
    await 1;
  }
  initSKU();
  visible.value = true;
};

const initSKU = (sku_cn_title = "", sku_en_title) => {
  let arr = languageOptions.value.sort((i, j) => {
    return i.id - j.id;
  });

  languages.value =
    formData.value.goods_sku[0].goods_sku_title?.length > 0
      ? formData.value.goods_sku[0].goods_sku_title
          .filter((i) => i.language_id != 1 && i.language_id != 2 && i.show)
          .map((valueObj) => valueObj.show && valueObj.language_id)
      : [];

  const newList = formData.value.goods_sku.map((i) => {
    const updatedValues = [];
    let existingLanguageIds = [];
    if (i.goods_sku_title && i.goods_sku_title.length > 0) {
      existingLanguageIds = i.goods_sku_title.map((valueObj) => valueObj.language_id);
      i.goods_sku_title.forEach((valueObj) => {
        const newValueObj = { ...valueObj };
        newValueObj.language_name = filterLanguage(newValueObj.language_id);
        if (!newValueObj.hasOwnProperty("show")) {
          newValueObj.show = true;
        }
        updatedValues.push(newValueObj);
      });
    }

    arr.forEach((j) => {
      if (!existingLanguageIds.includes(j.id)) {
        const copyValue = {
          specifications: i.sku_specification?.attributes
            ? Object.values(i.sku_specification.attributes).join(",")
            : "",
          title:
            j.id == 1
              ? sku_cn_title ||
                formData.value.spu_cn_title +
                  "_" +
                  Object.values(i.sku_specification.attributes).join(",")
              : j.id == 2
              ? sku_en_title || ""
              : "",
          language_id: j.id,
          language_code: j.short_name,
          language_name: j.name,
          show: j.id == 1 || j.id == 2,
        };
        updatedValues.push(copyValue);
      }
    });
    i.goods_sku_title = updatedValues;
    return i;
  });

  initGoodSku.value = newList;
};

const filterLanguage = (id) => {
  let item = languageOptions.value.find((i) => i.id == id);
  return item.name;
};

const languageSelect = ref([]);
// 选择语言把设置show属性
const changeLang = () => {
  languageSelect.value = selectLanguage(languages.value);
  initGoodSku.value.forEach((element, e) => {
    element.goods_sku_title.forEach((ele) => {
      if (ele.language_id > 2) {
        if (languageSelect.value.includes(ele.language_id)) {
          ele.show = true;
        } else {
          ele.show = false;
        }
      }
    });
  });
};
// 语言id
const selectLanguage = (list) => {
  let arr = [];
  list.forEach((item) => {
    languageOptions.value.forEach((o) => {
      if (item === o.id) {
        arr.push(o.id);
      }
    });
  });
  return arr;
};

// 翻译英语
const translate = () => {
  let arr = [];
  let list = initGoodSku.value;

  list &&
    list.forEach((item) => {
      arr.push(item.goods_sku_title[0].title);
    });
  let target_lang = [];
  languageOptions.value.forEach((o) => {
    languages.value.forEach((lang) => {
      if (o.id === lang && o.id != 1) {
        target_lang.push(o.short_name);
      }
    });
  });
  let languageArr = ["en"].concat(target_lang);
  let texts = {};
  languageArr.forEach((i) => {
    texts[i] = arr;
  });

  let param = {
    texts,
    use_proxy: true,
  };
  translationBatch(param).then((res) => {
    initGoodSku.value.forEach((att, index) => {
      att.goods_sku_title.map((item, i) => {
        if (res.data[item.language_code] && res.data[item.language_code].length) {
          item.title = res.data[item.language_code][index].trim();
        }
      });
    });
    ElMessage.success(res.message);
  });
};
const save = () => {
  initGoodSku.value.forEach((item) => {
    const cntitle = item.goods_sku_title.find((i) => i.language_id == 1);
    const entitle = item.goods_sku_title.find((i) => i.language_id == 2);
    item.sku_cn_title = cntitle?.title;
    item.sku_en_title = entitle?.title;
  });
  close();
};
const close = () => {
  visible.value = false;
};

defineExpose({ open, initSKU });
</script>
<style lang="scss" scoped>
.itemStyle {
  min-width: 80px;
  flex: auto;

  .inputStyle {
    height: 49px;

    .attribute {
      height: 32px;
      display: inline-block;
      line-height: 32px;
    }
  }

  &:last-child {
    border-bottom: 0;

    .borHeader {
      border-right: 0;
      border-bottom: 0;
    }

    .inputStyle {
      border-right: 0;

      &:first-child {
      }
    }
  }
}

.borHeader {
  background: #fafafa;
  box-shadow: 0px 1px 0px 0px #e6e7e9;
  line-height: 48px;
  border-bottom: 0;
}

.w-190 {
  width: 190px;
}

.w-120 {
  width: 120px;
  text-align: center;
}
</style>
